package com.ease.util {

   import flash.external.ExternalInterface;

   /**
    * Gathers information about the user's browser and system if they are using
    * Chrome to access the client.
    */
   internal class ChromeBrowserInfo implements IBrowserInfo {
      private var _name:String = BrowserUtil.BROWSER_CHROME;
      private var _version:String = null;
      private var _os:String = null;
      private var _arch:String = null;
      private var _cookieEnabled:Boolean = false;

      private static const PLATFORM_INDEX:int = 1;
      private static const OS_INFO_INDEX:int = 2;
      private static const VERSION_INDEX:int = 4;

      public function get version():String {
         return _version;
      }

      public function get name():String {
         return _name;
      }

      public function get os():String {
         return _os;
      }

      public function get arch():String {
         return _arch;
      }

      public function get cookieEnabled():Boolean {
         return _cookieEnabled;
      }

      /**
       * Checks if the user is using Chrome, and if so, extracts information about the browser
       * and system.
       *
       * @return true if the user is using Chrome on a supported OS, false otherwise. If false
       * is returned, information about the browser and system are not guaranteed to exist.
       */
      public function detect(ua:String):Boolean {
         // 0: Full User Agent, eg. "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.864.0 Safari/535.2"
         // 1: Platform
         // 2: OS info
         // 3: Webkit version
         // 4: Chrome version
         // 5: Safari build

         var reg:RegExp = /Mozilla\/.*? \((Windows|X11)(.*?) AppleWebKit\/(\d.*?).*?Chrome\/(.*?) Safari\/(.*)/i;
         var uaTokens:Object = reg.exec(ua);

         //no user agent match
         if (uaTokens == null) {
            return false;
         }

         //Special case to parse X11 information
         if (uaTokens[PLATFORM_INDEX].toString() == "X11") {
            var reg2:RegExp = /.*(Linux) (.*?)(;|\))/i;
            var osTokens:Object = reg2.exec(uaTokens[OS_INFO_INDEX]);

            if (osTokens != null) {
               _os = osTokens[1];
               _arch = osTokens[2];
            } else {
               return false;//reject non-Linux X11 versions
            }
         } else {
            //there is no way to find the CPU architecture of non-Linux computers using
            //user agent string or javascript, but _arch is not used anywhere
            _os = uaTokens[PLATFORM_INDEX];
         }

         _version = uaTokens[VERSION_INDEX];
         _cookieEnabled = ExternalInterface.call("function() {return window.navigator.cookieEnabled;}");

         return true;
      }
   }

}